package com.asap.demo.mysql.util;

import com.alibaba.fastjson.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class StandardEvent implements Event {
	private static final Logger logger = LoggerFactory.getLogger(StandardEvent.class);

	/**
	 * @Fields: serialVersionUID  
	 * @Todo: TODO  
	 */ 
	private static final long serialVersionUID = -8073354183428410665L;
	private Map<String, Object> map = new LinkedHashMap<>();
	private List<String> fittedRules = new ArrayList<>();
	private String id;

	public StandardEvent() {
		//this.id = UUID.randomUUID().toString();
		//this.map.put("uuid", this.id);
	}
	
	public StandardEvent(Map<String, Object> map) {
		
		this.map.putAll(map);
	}
	
	/**
	 * 
	 * @param json json
	 * @return StandardEvent
	 */
	public static StandardEvent parse(String json) {
		StandardEvent event;
		try{
			 event = new StandardEvent(
					JsonParser.<String,Object>parseFrom(json));
			event.setId((String) event.getField("uuid"));
		}catch(JSONException e){
			logger.error("parse json error:"+json,e);

			throw e;
		}
		return event;
	}
	
	@Override
	public String getId() {
		
		return this.id;
	}

	@Override
	public Object getField(String fieldName) {

		return this.map.get(fieldName);
	}
	
	@Override
	public void addField(String fieldName, String fieldValue) {
		
		this.map.put(fieldName, fieldValue);
	}
	
	@Override
	public String toString() {
		
		return JsonParser.<String,Object>toJson(this.map);
	}
	
	void setId(String id) {
		
		this.id = id;
	}
	
	/**
	 * 
	 * @param fieldName field
	 * @param fieldValue value
	 */
	public void updateField(String fieldName, String fieldValue) {
		
		if (!this.map.containsKey(fieldName)) {
			return;
		}
		this.addField(fieldName, fieldValue);
	}

	public List<String> getFittedRules() {
		return fittedRules;
	}

	void setFittedRules(List<String> fittedRules) {
		this.fittedRules = fittedRules;
	}

	@Override
	public Map<String, Object> getAllFields() {

		return this.map;
	}
	
}
